package com.lizard.schedule.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.DimenRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.lizard.schedule.log.ScheduleLog;
import com.lizard.schedule.manager.AccountManager;
import com.lizard.schedule.manager.observer.ObserverIfaces;
import com.lizard.schedule.manager.observer.ObserverManager;
import com.lizard.schedule.persistence.db.table.ScheduleTbl;
import com.lizard.schedule.ui.activity.AboutActivity;
import com.lizard.schedule.ui.activity.HistoryActivity;
import com.lizard.schedule.ui.activity.LoginActivity;
import com.lizard.schedule.ui.activity.MainPageActivity;
import com.lizard.schedule.ui.activity.ModifyPwdActivity;
import com.lizard.schedule.ui.fragment.base.BaseFragment;
import com.lizard.schedule.utils.DeviceUtil;
import com.lizard.schedule.utils.ScheduleUtil;
import com.lizard.schedule.utils.ToastUtil;
import com.lizard.schedule.widget.ScheduleAlertDialog;
import com.lizard.schedule.R;
import com.lizard.schedule.widget.ScheduleToast;
import com.lizard.schedule.widget.socialshare.SocialSharePopupWindow;
import com.umeng.socialize.utils.Log;

/**
 * 首页左侧抽屉
 */
public class LeftDrawerFragment extends BaseFragment implements View.OnClickListener, ObserverIfaces.ReloadUnfinishedHistoryScheduleCount {

    private View mContentView;
    /**
     * 菜单：历史计划
     */
    private View mMenuHistory;

    /**
     * 菜单：分享
     */
    private View mMenuShare;

    /**
     * 菜单：修改密码
     */
    private View mMenuModifyPwd;

    /**
     * 菜单：关于
     */
    private View mMenuAbout;

    /**
     * 菜单：退出登录
     */
    private View mMenuLogout;

    /**
     * 菜单：登录账户
     */
    private View mMenuLogin;

    /**
     * 未完成数小红点
     */
    private TextView mUnfinishedCountTxt;

    private Handler mHandler;

    /**
     * AdMob广告位
     */
    private AdView mAdView;

    private View mMenus;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.drawer_left_content, container, false);
        initView();
        setViewClick();
        loadUnfinishedHistoryScheduleCount();
        initAdMob();
        return mContentView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        registerObservers();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    /**
     * 广告位初始化
     */
    private void initAdMob(){

//        if(AccountManager.getInstance().getLoginType() == AccountManager.LOGIN_TYPE_USER){
//            // 注册用户 不展示广告
//            mAdView.setVisibility(View.GONE);
//            return;
//        }

        mContentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                mContentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                int[] location = new int[2];
                mMenus.getLocationOnScreen(location);

                // 菜单底部离屏幕底部剩余高度
                int space = DeviceUtil.getScreenHeight() - location[1] - mMenus.getHeight();

                // 广告栏高度
                int adHeight = getResources().getDimensionPixelSize(R.dimen.left_drawer_adview_height);

                if (space >= adHeight) { // 空间足够 则显示广告位
                    AdRequest.Builder builder = new AdRequest.Builder();
                    if(ScheduleUtil.isDebuggable()){
                        // 调试时标记为测试
                        builder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
                    }
                    AdRequest adRequest = builder.build();
                    mAdView.setAdListener(adListener);
                    mAdView.loadAd(adRequest);
                } else { // 空间不足不显示广告位
                    mAdView.setVisibility(View.GONE);
                }
            }
        });

    }

    /**
     * admob广告位监听
     */
    private AdListener adListener = new AdListener() {
        @Override
        public void onAdClosed() {
            super.onAdClosed();
            ScheduleLog.v("admob", "onAdClosed");
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            super.onAdFailedToLoad(errorCode);
            ScheduleLog.v("admob", "onAdFailedToLoad errorCode:" + errorCode);
        }

        @Override
        public void onAdLeftApplication() {
            super.onAdLeftApplication();
            ScheduleLog.v("admob", "onAdLeftApplication");
        }

        @Override
        public void onAdOpened() {
            super.onAdOpened();
            ScheduleLog.v("admob", "onAdOpened");
        }

        @Override
        public void onAdLoaded() {
            super.onAdLoaded();
            ScheduleLog.v("admob", "onAdLoaded");
        }
    };

    /**
     * 注册观察者通知
     */
    private void registerObservers() {
        ObserverManager.getInstance().registerReloadUnfinishedHistoryScheduleCount(this);
    }

    /**
     * 注销观察者通知
     */
    private void unregisterObservers() {
        ObserverManager.getInstance().unregisterReloadUnfinishedHistoryScheduleCount(this);
    }

    private void initView() {
        mMenuHistory = mContentView.findViewById(R.id.menu_history);
        mMenuShare = mContentView.findViewById(R.id.menu_share);
        mMenuModifyPwd = mContentView.findViewById(R.id.menu_modify_pwd);
        mMenuLogout = mContentView.findViewById(R.id.menu_logout);
        mMenuLogin = mContentView.findViewById(R.id.menu_login);
        mUnfinishedCountTxt = (TextView) mContentView.findViewById(R.id.unfinished_count);
        mUnfinishedCountTxt.setVisibility(View.GONE);
        mMenuAbout = mContentView.findViewById(R.id.menu_about);
        mAdView = (AdView) mContentView.findViewById(R.id.ad_view);
        mMenus = mContentView.findViewById(R.id.menus);
        initLeftDrawerMenus();
    }

    private void setViewClick() {
        mMenuHistory.setOnClickListener(this);
        mMenuShare.setOnClickListener(this);
        mMenuModifyPwd.setOnClickListener(this);
        mMenuLogout.setOnClickListener(this);
        mMenuLogin.setOnClickListener(this);
        mMenuAbout.setOnClickListener(this);
    }

    /**
     * 左侧抽屉菜单项初始化
     */
    private void initLeftDrawerMenus() {
        if (AccountManager.getInstance().getLoginType() == AccountManager.LOGIN_TYPE_NOUSER) {        // 非注册用户
            mMenuHistory.setVisibility(View.VISIBLE);
            mMenuShare.setVisibility(View.VISIBLE);
            mMenuAbout.setVisibility(View.VISIBLE);
            mMenuModifyPwd.setVisibility(View.GONE);
            mMenuLogin.setVisibility(View.VISIBLE);
            mMenuLogout.setVisibility(View.GONE);
        } else if (AccountManager.getInstance().getLoginType() == AccountManager.LOGIN_TYPE_USER) {   // 注册用户
            mMenuHistory.setVisibility(View.VISIBLE);
            mMenuShare.setVisibility(View.VISIBLE);
            mMenuAbout.setVisibility(View.VISIBLE);
            if(AccountManager.getInstance().getThirdLoginType() == 0){
                mMenuModifyPwd.setVisibility(View.VISIBLE);
            } else{
                mMenuModifyPwd.setVisibility(View.GONE);
            }
            mMenuLogin.setVisibility(View.GONE);
            mMenuLogout.setVisibility(View.VISIBLE);
        } else { // 无任何登录记录 不应该打开此页面
            logOut(false);
        }
    }

    /**
     * 加载未结束的历史计划数
     */
    private void loadUnfinishedHistoryScheduleCount() {
        final int count = ScheduleTbl.getInstance().countUnfinishedHistoryScheduleCount(AccountManager.getInstance().getmUsernameMD5L16(), System.currentTimeMillis());
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (count > 0) {
                    mUnfinishedCountTxt.setVisibility(View.VISIBLE);
                    mUnfinishedCountTxt.setText(ScheduleUtil.transferCountInRedPoint(count));
                } else {
                    mUnfinishedCountTxt.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterObservers();
    }

    @Override
    public void onClick(View v) {
        if (v == mMenuHistory) {
            startHistoryPage();
        } else if (v == mMenuShare) {
            share();
        } else if (v == mMenuModifyPwd) {
            modifyPwd();
        } else if (v == mMenuLogout) {
            logOut(true);
        } else if (v == mMenuLogin) {
            login();
        } else if (v == mMenuAbout) {
            startAboutPage();
        }
    }

    /**
     * 进入“关于”页
     */
    private void startAboutPage(){
        startActivity(new Intent(getActivity(), AboutActivity.class));
    }

    /**
     * 修改密码
     */
    private void modifyPwd() {
        ((MainPageActivity) getActivity()).closeLeftDrawer();
        startActivity(new Intent(getActivity(), ModifyPwdActivity.class));
    }

    /**
     * 分享
     */
    private void share() {

        ((MainPageActivity) getActivity()).closeLeftDrawer();

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                if (getActivity() != null) {
                    new SocialSharePopupWindow(getActivity(),
                            getActivity().getWindow().getDecorView())
                            .show();
                }
            }
        }, 200);

    }

    /**
     * 登录账户(单机用户登录账户)
     */
    private void login() {
        AccountManager.getInstance().logOut();
        startActivity(new Intent(getActivity(), LoginActivity.class));
        getActivity().finish();
    }

    /**
     * 退出登录
     *
     * @param alert 是否alert提示
     */
    public void logOut(boolean alert) {

        ((MainPageActivity) getActivity()).closeLeftDrawer();

        if (alert) {
            new ScheduleAlertDialog.Builder(getActivity())
                    .setMessage(R.string.sure_logout)
                    .setPositiveButton(R.string.confirm, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            logOut();
                        }
                    })
                    .setNegativeButton(R.string.cancel, null).show();
        } else {
            logOut();
        }
    }

    /**
     * 退出登录
     */
    private void logOut() {
        AccountManager.getInstance().logOut();
        startActivity(new Intent(getActivity(), LoginActivity.class));
        getActivity().finish();
    }

    /**
     * 计入历史计划页
     */
    private void startHistoryPage() {
        startActivity(new Intent(getActivity(), HistoryActivity.class));
    }

    @Override
    public void reload() {
        loadUnfinishedHistoryScheduleCount();
    }
}
